package cn.com.sinux.spring.utils;

import cn.com.sinux.spring.commons.SpringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;

import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

/**
 * Created with IntelliJ IDEA. User: New Date: 13-1-29 Time: 下午4:58 To change
 * this template use File | Settings | File Templates.
 */
public class ResourceUtils {

    private final static Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

    /**
     * 获取国际化信息
     *
     * @param codes
     * @param locale
     * @return
     */
    public static String getMsg(List<String> codes, Locale locale) {
        if (codes.isEmpty()) {
            return StringUtils.EMPTY;
        }
        MessageSource messageSource = SpringUtils.getBean("messageSource");
        List<String> msgs = new LinkedList<String>();

        for (String _code : codes) {
            try {
                msgs.add(messageSource.getMessage(_code, null, locale));
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
                msgs.add(_code);
            }
        }
        return StringUtils.join(msgs, ',');
    }

    /**
     * 获取国际化信息
     *
     * @param code
     * @param locale
     * @return
     */
    public static String getMsg(String code, Locale locale) {
        if (StringUtils.isBlank(code)) {
            return StringUtils.EMPTY;
        }
        MessageSource messageSource = SpringUtils.getBean("messageSource");
        try {
            return messageSource.getMessage(code, new String[0], locale);
        } catch (Exception ex) {
            logger.error("{}", code);
            logger.debug(ex.getMessage(), ex);
            //国际化代码直接调用
            return code;
            // return messageSource.getMessage("00x001", new String[0], locale);
        }
    }
}
